// pages/starDetail/starDetail.js
const app = getApp()
let interstitialAd = null
let videoAd = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    msg: '',
    modalName: '',
    starId: '',
    numx: 1,
    getbtm: false,
    lastvote: 0,
    pic: '',
    starName: '',
    yqType: '',
    Isnewtype: '',
    Userid: '',
    yaoqing: '',
    now: '',
    is_subscribe: '',
    vote_remain: '',
    sharepic: '',
    page: 1,
    show: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("哈哈哈", options);

    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-0ded053be4dfaa91'
      })
      interstitialAd.onLoad(() => {})
      interstitialAd.onError((err) => {})
      interstitialAd.onClose(() => {})
    }
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-a6a4949833b1ac4d'
      })
      videoAd.onLoad(() => {})
      videoAd.onError((err) => {})
      videoAd.onClose((res) => {})
    }
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000000',
      animation: {
        duration: 0,
        timingFunc: 'easeIn'
      }
    })
    console.log(options, "数据")
    if (options.scene) {
      this.setData({
        starId: options.scene,
        // Isnewtype: 0,
        // yaoqing: '1'
      })
    } else {
      if (options.isnewMan == 'newman') {
        this.setData({
          Isnewtype: 1,
          yaoqing: '1'
        })
      } else if (options.isnewMan == 'haoyou') {
        this.setData({
          Isnewtype: 0,
          yaoqing: '1'
        })
      }
      if (options.fromUserId) {
        this.setData({
          Userid: options.fromUserId
        })
      }
      this.setData({
        starId: options.id,
      })

    }
    this.getShow(options)
    this.getsharepic()
  },
  video() {
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频 广告显示失败')
          })

      })
    }
  },
  getvisit() {
    let token = wx.getStorageSync('userinfo').token

    console.log(token)
    if (token) {
      app.post_request('User/visit').then(res => {
        if (res.data.status == 200) {
          wx.showToast({
            title: '登录票数+5'
          })

        }
      })
    }

  },
  getsharepic() {
    const ctx = wx.createCanvasContext('canvas')
    let that = this
    ctx.setFillStyle('#fff')
    ctx.fillRect(0, 0, 375, 300)
    wx.getImageInfo({
      src: 'https://lovewall.needyoutd.com/starmedia/suibian.png',
      success(res) {
        console.log(res)
        wx.getImageInfo({
          src: that.data.pic,
          success(resx) {

            ctx.drawImage(res.path, 0, 0, 750, 600)
            ctx.beginPath()
            ctx.arc(375, 300, 189, 0, 3.6 * Math.PI)
            ctx.clip()
            ctx.drawImage(resx.path, 186, 108, 380, 380)
            ctx.restore()

            ctx.draw(true, res => {
              wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: 750,
                height: 600,
                destWidth: 750,
                destHeight: 600,
                fileType: 'png',
                canvasId: 'canvas',
                success(res) {
                  console.log(res.tempFilePath, "嘻嘻")
                  that.setData({
                    sharepic: res.tempFilePath
                  })
                  // wx.uploadFile({
                  //   filePath: res.tempFilePath,
                  //   name: 'imgFile',
                  //   // formData:{
                  //   //   imgFile:res.tempFilePath
                  //   // },
                  //   url: 'https://lovewall.needyoutd.com/api/Poster/upload',
                  //   success(res){
                  //     console.log(JSON.parse(res.data).data.imgUrl,'返回的')
                  //     that.setData({
                  //       sharepic:JSON.parse(res.data).data.imgUrl
                  //     })
                  //   }
                  // })
                }
              })
              console.log(res)
            })
          }
        })

      }
    })

  },
  now(e) {
    console.log(e)
    this.setData({
      now: e.detail.value
    })
  },
  check() {
    let that = this
    let data = {
      link: this.data.now,
      starId: parseInt(this.data.starId)
    }
    console.log(typeof (this.data.now))
    app.post_request('Weibo/check', data).then(res => {
      if (res.data.status == 200) {
        that.getShow()
        wx.showToast({
          title: '操作成功',
          icon: 'none'
        })
        that.setData({
          modalName: ''
        })
      } else if (res.data.status == 1000) {
        wx.showToast({
          title: '请填写链接',
          icon: 'none'
        })
      } else if (res.data.status == 10019) {
        wx.showToast({
          title: '帖子格式错误',
          icon: 'none'
        })
      } else if (res.data.status == 10021) {
        wx.showToast({
          title: '今日已发过贴',
          icon: 'none'
        })
      } else if (res.data.status == 10018) {
        wx.showToast({
          title: '不是今日发帖',
          icon: 'none'
        })
      }

    })
  },
  turn_poster() {
    let that = this
    this.invitational()
    wx.navigateTo({
      url: '../poster/poster?id=' + this.data.starId + '&isnewMan=' + this.data.yqType + '&fromUserId=' + wx.getStorageSync('userinfo').id + '&backImg=' + this.data.pic + '&name=' + this.data.starName,
    })
    if (this.data.yaoqing == "1") {

      return
    }


  },
  back() {
    wx.navigateTo({
      url: '/pages/index/index',
    })


  },
  invitational() {
    let that = this
    if (that.data.yaoqing == '1') {
      wx.getUserProfile({
        desc: '获取您的用户名和头像',
        success(resu) {
          wx.showLoading({
            title: '授权中',
          })
          console.log(Number(that.data.Userid), "上海市")
          wx.login({
            success(resl) {
              console.log(resl)
              let userdata = {
                code: resl.code,
                nickName: resu.userInfo.nickName,
                avatarUrl: resu.userInfo.avatarUrl,
                invitation: that.data.Isnewtype,
                fromUserId: Number(that.data.Userid)
              }
              app.post_request('Login', userdata).then(resz => {
                wx.hideLoading()
                wx.showToast({
                  title: '授权成功',
                  icon: 'none'
                })
                wx.setStorage({
                  data: resz.data.data,
                  key: 'userinfo',
                  success() {
                    that.setData({
                      yaoqing: ''
                    })
                    console.log(that.data.yaoqing)
                    that.getShow()
                  }
                })
              })
            }
          })
        }
      })
    } else if (!wx.getStorageSync('userinfo').token) {
      wx.getUserProfile({
        desc: '获取您的用户名和头像',
        success(resu) {
          wx.showLoading({
            title: '授权中',
          })
          console.log(Number(that.data.Userid), "上海市")
          wx.login({
            success(resl) {
              console.log(resl)
              let userdata = {
                code: resl.code,
                nickName: resu.userInfo.nickName,
                avatarUrl: resu.userInfo.avatarUrl,
              }
              app.post_request('Login', userdata).then(resz => {
                wx.hideLoading()
                wx.showToast({
                  title: '授权成功',
                  icon: 'none'
                })
                wx.setStorage({
                  data: resz.data.data,
                  key: 'userinfo',
                  success() {
                    that.setData({
                      yaoqing: ''
                    })
                    console.log(that.data.yaoqing)
                    that.getShow()
                  }
                })
              })
            }
          })
        }
      })
    }
  },
  showModal(e) {
    let that = this
    that.invitational()
    if (that.data.yaoqing == "1") {
      console.log("yaoqing")

      return
    }
    let token = wx.getStorageSync('userinfo').token
    if (e.currentTarget.dataset.target == "Xryq") {

      app.get_request('NewUser/list?page=' + 1, token).then(res => {
        that.setData({
          newUserList: res.data.data.newUserList,
          howpelo: res.data.data.count,
          yqType: 'newman'
        })
        console.log(res)
      })
    } else if (e.currentTarget.dataset.target == "yqhy") {
      app.get_request('Friend/list', token).then(res => {
        let num = 10 - parseInt(res.data.data.count)
        let friendList = res.data.data.friendList
        console.log(num)
        for (let i = 0; i < num; i++) {
          friendList.push({
            header: 1
          })
        }
        console.log(friendList)
        that.setData({
          friendList: friendList,
          friendListcount: res.data.data.count,
          yqType: 'haoyou'
        })
        console.log(res)
      })
    } else if (e.currentTarget.dataset.target == "blog") {
      app.get_request('Weibo/template?starId=' + this.data.starId).then(res => {
        console.log(res)
        that.setData({
          weibo_template: res.data.data.weibo_template
        })
      })
    }
    that.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  scroll(e) {


  },
  turn_web() {
    wx.navigateTo({
      url: '/pages/webView/webView?id=dk',
    })
  },
  copyText(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success(res) {
        wx.getClipboardData({
          success(res) {
            console.log(res.data) // data
          }
        })
      }
    })
  },
  lower(e) {
    let that = this
    if (e.detail.direction == "bottom") {
      let token = wx.getStorageSync('userinfo').token
      let newUserList = that.data.newUserList
      console.log(e, "lower")
      console.log(that.data.numx)
      let numx = (that.data.numx += 1)
      app.get_request('NewUser/list?page=' + numx, token).then(res => {
        if (res.data.data.newUserList.length == 0) {
          that.setData({
            getbtm: true
          })
        } else {
          that.setData({
            newUserList: [...newUserList, ...res.data.data.newUserList],
            numx: numx
          })
          console.log(res)
        }
      })
    }

  },
  turn_yq(e) {
    console.log(e.currentTarget.dataset.name)
    this.setData({
      turn_yq: e.currentTarget.dataset.name
    })
  },
  getShow(e) {
    let that = this
    let tok = wx.getStorageSync('userinfo').token
    app.get_request('Message/list?starId=' + that.data.starId, tok).then(res => {
      console.log(res)
      if (res.data.status == 200) {
        that.setData({
          msgdata: res.data.data.messageList,
          leaveing: res.data.data.count
        })
      }

    })
    app.get_request('Star/index?starId=' + that.data.starId).then(res => {
      that.setData({
        pic: res.data.data.photo,
        vote: res.data.data.count,
        starName: res.data.data.name,
        num: res.data.data.ranking,
      })
      if (res.data.data.lastStar !== null) {
        that.setData({
          lastvote: res.data.data.lastStar.gap
        })
      }
    })
    app.get_request('UserVote/index', tok).then(res => {
      that.setData({
        vote_remain: res.data.data.vote_remain,
        is_post: res.data.data.is_post,
        is_clockIn: res.data.data.is_clockIn,
        available: res.data.data.available,
        is_subscribe: res.data.data.is_subscribe
      })
      console.log(res)
    })
    this.getvisit()
  },
  addvote(e) {
    let that = this
    console.log(e)
    let data = {
      starId: this.data.starId,
      num: parseInt(e.currentTarget.dataset.vote)
    }
    that.invitational()
    if (that.data.yaoqing == "1") {
      console.log('jinlai')
      return
    }
    console.log(that.data.is_subscribe, "哈哈哈")
    wx.requestSubscribeMessage({
      tmplIds: ['ilGv0-VtbSYrGqQ9uLiyNRSGgEjhC4KOzEnyJ6mbQh0', 'Bo2T8NLW-aLibx1maPNE7WmBzAxJxJ9muC_1NzkOI3M'],
      success(resx) {
        if (resx['ilGv0-VtbSYrGqQ9uLiyNRSGgEjhC4KOzEnyJ6mbQh0'] == "accept") {
          app.post_request('User/subscribe').then(res => {
            that.getShow()
          })
        }
        app.post_request('VoteRecord/add', data).then(res => {
          console.log(res)
          if (res.data.status == 10013) {
            that.setData({
              modalName: 'Tpmei'
            })

          } else if (res.data.status == 200) {
            console.log("Shss")
            that.setData({
              modalName: 'tpsucc'
            })
            console.log(that.data.modalName)
            setTimeout(res => {
              that.getShow(that.data.starId)
            }, 500)

          } else if (res.data.status == 10005) {
            that.wxlogin()
          } else if (res.data.status == 10022) {
            wx.showToast({
              title: '投票未开始',
              icon: 'none'
            })
          } else if (res.data.status == 10016) {
            wx.showToast({
              title: '投票已结束',
              icon: 'none'
            })
          }
        })
      }
    })
    // app.post_request('VoteRecord/add', data).then(res => {
    //   if (res.data.status == 10013) {
    //     that.setData({
    //       modalName: 'Tpmei'
    //     })
    //   } else if (res.data.status == 200) {
    //     that.setData({
    //       modalName: 'tpsucc'
    //     })
    //     setTimeout(res => {
    //       that.getShow(that.data.starId)
    //     }, 500)

    //   } else if (res.data.status == 10005) {
    //     that.wxlogin()
    //   } else if (res.data.status == 10022) {
    //     wx.showToast({
    //       title: '投票未开始',
    //       icon: 'none'
    //     })
    //   }
    // })


    console.log(e)
  },
  turn_morevote() {
    var me = this;
    this.setData({
      modalName: ''
    })
    var query = wx.createSelectorQuery().in(me);
    console.log(query)
    query.selectViewport().scrollOffset()
    query.select("#comment").boundingClientRect();
    query.exec(function (res) {
      console.log(res);
      var miss = res[0].scrollTop + res[1].top - 10;
      wx.pageScrollTo({
        scrollTop: miss,
        duration: 300
      });

    });
  },
  wxlogin() {
    wx.getUserProfile({
      desc: '获取您的用户名和头像',
      success(resu) {
        wx.showLoading({
          title: '授权中',
        })
        wx.login({
          success(resl) {
            console.log(resl)
            let userdata = {
              code: resl.code,
              nickName: resu.userInfo.nickName,
              avatarUrl: resu.userInfo.avatarUrl
            }
            app.post_request('Login', userdata).then(resz => {
              wx.hideLoading()
              wx.showToast({
                title: '授权成功',
                icon: 'none'
              })
              wx.setStorage({
                data: resz.data.data,
                key: 'userinfo',
                success() {
                  that.getShow()

                }
              })
            })
          }
        })
      }
    })
  },
  leaveAmessage() {
    let that = this
    wx.showLoading({
      title: '留言中',
    })
    let data = {
      starId: this.data.starId,
      content: this.data.msg
    }
    app.post_request('Message/add', data).then(res => {
      wx.hideLoading({
        success: (res) => {},
      })
      console.log(res)
      if (res.data.status === 200) {
        wx.showToast({
          title: '内容审核后将展示在留言列表',
          icon: 'none',
          duration: 2000
        })
        that.getShow()

      } else if (res.data.status === 10011) {
        wx.showToast({
          title: '铭感词汇',
          icon: 'none'
        })
      } else if (res.data.status == 10007) {
        wx.showToast({
          title: '投票后在留言',
          icon: 'none'
        })
      }
    })
  },
  hideModel() {
    this.setData({
      modalName: ''
    })
  },
  open_vote(e) {
    console.log(e.currentTarget.dataset.vote)
    if (this.data.vote_remain < e.currentTarget.dataset.vote) {
      console.log("俩")
      this.setData({
        modalName: 'Tpmei'
      })
    } else {
      this.setData({
        modalName: 'addvote',
        vote_type: e.currentTarget.dataset.vote
      })
    }

  },
  val(e) {
    console.log(e)
    this.setData({
      msg: e.detail.value
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    let token = wx.getStorageSync('userinfo').token
    videoAd.onClose(res => {
      if (res.isEnded) {
        app.post_request('User/watchVideo').then(res => {
          console.log(res.data.status)
          if (res.data.status == 200) {
            that.getShow()
            wx.showToast({
              title: '观看完成,票数+3',
              icon: 'none'
            })
          } else if (res.data.status == 10014) {
            wx.showToast({
              title: '今日观看视频次数已达上限',
              icon: 'none'
            })
          }
        })

      } else {
        wx.showToast({
          title: '请观看完整视频',
          icon: 'none'
        })
      }
      console.log(res)
    })

  },

  // Adduser(){
  //   this.invitational()
  //   this.setData({
  //     show:false
  //   })
  // },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this
    let tok = wx.getStorageSync('userinfo').token
    this.data.page += 1
    let page = this.data.page
    let msgdata = this.data.msgdata
    app.get_request('Message/list?starId=' + that.data.starId + '&page=' + page, tok).then(res => {
      console.log(res)
      if (res.data.status == 10017) {

      } else if (res.data.data.messageList.length == 0) {
        wx.showToast({
          title: '没有更多啦',
          icon: 'none'
        })
      }
      that.setData({
        msgdata: [...msgdata, ...res.data.data.messageList]
      })
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;

    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: this.data.starName + "正在参与最具影响力偶像，一起来投票吧", // 默认是小程序的名称(可以写slogan等)
      path: '/pages/starDetail/starDetail?id=' + this.data.starId + '&isnewMan=' + this.data.yqType + '&fromUserId=' + wx.getStorageSync('userinfo').id, // 默认是当前页面，必须是以‘/’开头的完整路径
      imageUrl: this.data.sharepic, //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success(res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {}
      },
      fail() {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete() {
        // 转发结束之后的回调（转发成不成功都会执行）
      }
    }
    // 来自页面内的按钮的转发

    // 返回shareObj
    return shareObj
  }
})